package com.dylan.shot.head.service.impl;

import com.dylan.shot.common.model.Member;
import com.dylan.shot.common.service.MemberService;
import com.dylan.shot.head.service.MemberAuthenticateService;
import com.dylan.shot.head.shiro.ShiroHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Dylan on 2017/9/12.
 */
@Service
public class MemberAuthenticateServiceImpl implements MemberAuthenticateService {
    @Autowired
    private MemberService memberService;

    @Override
    public void createMember(Member member) {
        if (StringUtils.isBlank(member.getUsername()) && StringUtils.isBlank(member.getPhone()) && StringUtils.isBlank(member.getEmail())) {
            throw new RuntimeException("创建会员,username,phone,email不能全为空");
        }
        if (StringUtils.isBlank(member.getPassword())) {
            throw new RuntimeException("创建会员,password不能为空");
        }
        member.setPassword(ShiroHelper.encryptPassword(member.getPassword()));
        memberService.insertUseGeneratedKey(member);
    }

    @Override
    public Member getMemberByUsername(String username) {
        if (StringUtils.isBlank(username)) {
            throw new RuntimeException("查询会员,username不能为空");
        }
        Member member = new Member();
        member.setUsername(username);
        return memberService.selectOne(member);
    }

    @Override
    public Member getMemberByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new RuntimeException("查询会员,phone不能为空");
        }
        Member member = new Member();
        member.setPhone(phone);
        return memberService.selectOne(member);
    }

    @Override
    public Member getMemberByEmail(String email) {
        if (StringUtils.isBlank(email)) {
            throw new RuntimeException("查询会员,email不能为空");
        }
        Member member = new Member();
        member.setEmail(email);
        return memberService.selectOne(member);
    }

    @Override
    public void updateMemberByMemberId(Member member) {
        if (member.getMemberId() == null) {
            throw new RuntimeException("更新会员,memberId不能为空");
        }
        if (StringUtils.isNotBlank(member.getPassword())) {
            member.setPassword(ShiroHelper.encryptPassword(member.getPassword()));
            // 修改密码,清空认证缓存
            ShiroHelper.clearCached(member);
        }
        memberService.updateByKey(member);
        // 更新到session
        ShiroHelper.updateCachedWorker(member);
    }
}
